/**
* @program: src
*
* @description:初始化rpc
*
* @author: Mr.chen
*
* @create: 2020-12-19 10:53
**/
package sysinit
import (
	"os"
	"ydd-im/service/account/handler"
	"ydd-im/service/account/proto"
	"ydd-im/service/api/define"
	"ydd-im/service/api/pkg/etcd"
	"ydd-im/service/api/tools/util"
	"fmt"
	"net"
	"google.golang.org/grpc"
	"ydd-im/util/interceptor/jaegerinterceptor"
)
//ETCD注册发现服务
func RegisterServer() {
	//注册租约
	ser, err := etcd.NewServiceReg(define.EtcdEndpoints, 5)
	if err != nil {
		panic(err)
	}
	hostPort := net.JoinHostPort(define.LocalHost, define.RPCPort)
	//fmt.Println(define.EtcdEndpoints,define.LocalHost,define.RPCPort,define.ETCD_SERVER_LIST+hostPort,hostPort)
	//添加key,创建account服务
	err = ser.PutService(define.ETCD_SERVER_Account_LIST+hostPort, hostPort)
	if err != nil {
		panic(err)
	}
	cli, err := etcd.NewClientDis(define.EtcdEndpoints)
	if err != nil {
		panic(err)
	}
	// 获取当前群的地址，监听account的key值
	_, err = cli.GetService(define.ETCD_SERVER_Account_LIST)
	if err != nil {
		panic(err)
	}
	// 获取dbproxy地址，监听fbproxy的key值
	_, err = cli.GetService(define.ETCD_SERVER_Dbproxy_LIST)
	if err != nil {
		panic(err)
	}
}
func initGRpcServerPlus(port string) {
	define.RPCPort = port
	go createGRPCServer(":" + port)
}
func InitRPCServer(port string) {
	//如果是集群，则启用RPC进行通讯
	//初始化RPC服务
	rpcPort := util.GenRpcPort(port)
	initGRpcServerPlus(rpcPort)
	fmt.Println(fmt.Printf("启动RPC，端口号：%s\n", rpcPort))

}
// 创建grpc服务
func createGRPCServer(port string) {
	var serviceOpts []grpc.ServerOption
	// 链路追踪
	tracer, _, err := jaegerinterceptor.NewJaegerTracer("yd-im-account", "127.0.0.1:6831")
	if err != nil {
		fmt.Printf("new tracer err: %+v\n", err)
		os.Exit(-1)
	}
	if tracer != nil {
		serviceOpts = append(serviceOpts, jaegerinterceptor.ServerOption(tracer))
	}

	Handler := &handler.Controller{}
	lis, err := net.Listen("tcp", port)
	if err != nil {
		panic(err)
	}
	s := grpc.NewServer(serviceOpts...)
	proto.RegisterUserAccountServiceServer(s,Handler)
	err = s.Serve(lis)
	if err != nil {
		panic(err)
	}
}





